//
//  XZNoticeDetailVC.m
//  优学荟管理系统
//
//  Created by edz on 2018/1/22.
//  Copyright © 2018年 星道三好. All rights reserved.
//

#import "XZNoticeDetailVC.h"
#import <SDWebImage/UIButton+WebCache.h>
#import "ImgZoom.h"
#import "EMCDDeviceManager.h"

@interface XZNoticeDetailVC ()<UIWebViewDelegate>
//通告标题
@property (weak, nonatomic) IBOutlet UILabel *notice_title;
//通告时间
@property (weak, nonatomic) IBOutlet UILabel *time;
//通告内容
@property (weak, nonatomic) IBOutlet UILabel *content;
//音视频数组
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *audioVideoArr;
// 最外层view的高度
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *backRandHeight;

@property (nonatomic, strong) UIWebView *webView;

@property (nonatomic, strong) NSMutableArray *DataArr;
@end

@implementation XZNoticeDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"通告详情";
    
    [self setnetWork];
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTargat:self action:@selector(leftBarButtonItemAction) image:@"icon_back_student_sign" highImage:@"icon_back_student_sign"];
}



-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:ColorRGB(255,255,255)}]; //设置标题颜色
    [self.navigationController.navigationBar setBackgroundImage:[LLTools createImageWithColor:ColorRGB(47, 204, 138)] forBarMetrics:(UIBarMetricsDefault)];//设置导航栏颜色
    
    [SVProgressHUD dismiss];
}


- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self.navigationController.navigationBar setBackgroundImage:[LLTools createImageWithColor:ColorRGB(255, 255, 255)] forBarMetrics:(UIBarMetricsDefault)];//设置导航栏颜色
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:ColorRGB(51,51,51)}];//设置标题颜色
}

- (void)leftBarButtonItemAction{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setnetWork {
    ///http://192.168.0.226:8080/StarShine/ys/assignHomework.do?action=getOrganizationAnnunciateById&id=
    
    [SVProgressHUD showWithStatus:@"正在加载..."];
    NSString *url = [NSString stringWithFormat:@"assignHomework.do?action=getOrganizationAnnunciateById&id=%@",self.ID];
    [NetManager Get:LLBaseURL(url) Auth:YES Params:nil Success:^(id Obj) {
        if ([[Obj[@"code"] stringValue] isEqualToString:@"1000"]) {
            NSDictionary *dict = Obj[@"t"];
            XZNotificationModel *model = [[XZNotificationModel alloc] init_ValuForKeyWithDict:dict];
            self.model = model;
            [self setupUI];
        } else {
            [SVProgressHUD showErrorWithStatus:Obj[@"msg"]];
        }
        [SVProgressHUD dismiss];
    } Fail:^(NSError *Error) {
        [SVProgressHUD dismiss];
    }];
}




- (void)setupUI {
    _notice_title.text = _model.title;
    _time.text = _model.createTime;
    _content.text = _model.content;
    //内容文字的高度
    CGSize titleSize = [_content.text sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(_content.width, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
    /// 判断是否有视频url
    if (self.model.video != nil && ![self.model.video isKindOfClass:[NSNull class]] && self.model.video.length > 0) {
        
        [self.DataArr addObject:self.model.video];
    }
    ///添加照片 音视频
    [self.DataArr addObjectsFromArray:self.model.paths];
    /// 循环判断 音频 和 照片
    [self.DataArr enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        UIButton *btn = _audioVideoArr[idx];
        btn.hidden = NO;
        NSString *Str = [obj pathExtension];
        if ([Str isEqualToString:@"png"] || [Str isEqualToString:@"jpg"]) {
            [btn sd_setBackgroundImageWithURL:[NSURL URLWithString:obj] forState:(UIControlStateNormal) placeholderImage:[UIImage imageNamed:@"bg_img_homework_picture_default"] options:SDWebImageContinueInBackground];
            btn.tag = 1001;
        } else if ([Str isEqualToString:@"amr"] || [Str isEqualToString:@"mp3"]) {
            [btn setBackgroundImage:[UIImage imageNamed:@"btn_mp3"] forState:(UIControlStateNormal)];
            btn.tag = 1002;
        } else {
            btn.tag = 1003;
            [btn sd_setBackgroundImageWithURL:[NSURL URLWithString:self.model.videoImg] forState:(UIControlStateNormal) placeholderImage:[UIImage imageNamed:@"bg_img_homework_picture_default"] options:SDWebImageContinueInBackground];
        }
    }];
    
    int imageHeigth = self.DataArr.count != 0 ? 80 : 0;
    _backRandHeight.constant = 110 + _notice_title.height + _time.height + titleSize.height + imageHeigth;
}

- (IBAction)ClickPlay:(UIButton *)sender {
    /// 1.放图片 2.播放音频 3.播放视频
    switch (sender.tag) {
        case 1001:
            [ImgZoom MgrButtonImgView:sender];
            break;
        case 1002:
        {
            [self.DataArr enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSString *Str = [obj pathExtension];
            if ([Str isEqualToString:@"amr"] || [Str isEqualToString:@"mp3"]) {
                [self PlayerWithUrlStr:obj];
            }
            }];
            
        }
            
            break;
        case 1003:
            [self.webView loadRequest:[[NSURLRequest alloc]initWithURL:[NSURL URLWithString:self.model.video]]];
            self.webView.hidden =NO;
            break;
        default:
            break;
    }
}

- (void)PlayerWithUrlStr:(NSString *)UrlStr
{
    if ([EMCDDeviceManager sharedInstance].isPlaying) {
        [[EMCDDeviceManager sharedInstance] stopPlaying];
    } else {
        [self RefreshDataForAmr:UrlStr Complete:^(NSString *FullPath) {
            
            FullPath = [FullPath substringFromIndex:7];
            [[EMCDDeviceManager sharedInstance] asyncPlayingWithPath:FullPath completion:^(NSError *error) {
                NSLog(@"播放完成");
            }];
        }];
    }
}

- (void)RefreshDataForAmr:(NSString *)UrlStr Complete:(void(^)(NSString *FullPath))Complete
{
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"AMR"];
    [NetManager DownLoadFileWithUrlStr:UrlStr FileName:[UrlStr lastPathComponent] Path:path Progress:^(CGFloat Index) {
        
    } Complete:^(NSString *FullPath, NSError *Err) {
        [MBProgressHUD hideHUD];
        if (Err)
        {
            [MBProgressHUD showError:@"音频文件播放失败"];
        }
        else
        {
            Complete (FullPath);
        }
    }];
    
}

#pragma mark UIWebDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    self.webView =nil;
}



- (UIWebView *)webView{
    if (_webView == nil) {
        self.webView = [[UIWebView alloc]initWithFrame:CGRectMake(1, 1, 1, 1)];
        self.webView.delegate =self;
        [self.view addSubview:self.webView];
    }
    return _webView;
}




- (NSMutableArray *)DataArr {
    if (!_DataArr) {
        _DataArr = @[].mutableCopy;
    }
    return _DataArr;
}

@end
